package main

import (
	"fmt"
	"iot-cloud-server/consumer"
	"iot-cloud-server/mongodb"
	"iot-cloud-server/netserver"
	"sync"
)

// rabbitmq and mongodb relative
var (
	// rabbitmq config
	amqpURI      string = "amqp://guest:guest@localhost:5672/"
	exchange     string = "makeblock-iot-topics"
	exchangeType string = "topic"
	queueName    string = "mongo-queue"
	routingKey   string = "#"
	consumerTag  string = "rabbitmq-mongo-consumer"
	//mongodb config
	mongoURI string = "127.0.0.1:27020"
)

func RabbitmqRun(db *mongodb.MongoServer, wg *sync.WaitGroup) error {
	c, err := consumer.NewConsumer(amqpURI, db, wg)
	if err != nil {
		fmt.Println("NewConsumer %s", err)
		return err
	}

	err = c.DeclareAndBindExchangeQueue(exchange, exchangeType, queueName, routingKey)
	if err != nil {
		fmt.Println("DeclareAndBindExchangeQueue %s", err)
		return err
	}

	err = c.Consume(queueName, consumerTag)
	if err != nil {
		fmt.Println("Consume %s", err)
		return err
	}
	return nil
}

func main() {

	var err error
	var wg sync.WaitGroup
	db, err := mongodb.NewMongoServer(mongoURI, &wg)
	if err != nil {
		fmt.Println("Create mongodb driver failed %s", err)
		return
	}
	err = RabbitmqRun(db, &wg)
	if err != nil {
		fmt.Println("RabbitmqRun %s", err)
		return
	}

	netserver.NetServerRun(db, &wg)

	//wg.Wait()

	fmt.Println("main routine finished")
	return
}
